package com.wl.nio;

import org.junit.Test;

import java.io.IOException;
import java.net.InetSocketAddress;
import java.nio.ByteBuffer;
import java.nio.channels.DatagramChannel;
import java.nio.channels.SelectionKey;
import java.nio.channels.Selector;
import java.time.LocalDateTime;
import java.util.Iterator;
import java.util.Scanner;

public class TestNonBlockingNIO2 {
    @Test
    public void send(){
        try {
            DatagramChannel dc = DatagramChannel.open();
            dc.configureBlocking(false);
            ByteBuffer buf = ByteBuffer.allocate(1024);
            Scanner scanner = new Scanner(System.in);
            while (scanner.hasNext()){
                String str = scanner.next();
                buf.put((LocalDateTime.now().toString()+":\n"+str).getBytes());
                dc.send(buf,new InetSocketAddress("127.0.0.1",9898));
                buf.clear();
            }
            dc.close();
        } catch (IOException e) {
            e.printStackTrace();
        }

    }

    @Test
    public void receive(){
        try {
            DatagramChannel dc = DatagramChannel.open();
            dc.configureBlocking(false);
            dc.bind(new InetSocketAddress(9898));
            Selector selector = Selector.open();
            dc.register(selector, SelectionKey.OP_READ);
            while (selector.select() > 0){
                Iterator<SelectionKey> it = selector.selectedKeys().iterator();
                while (it.hasNext()){
                    SelectionKey sk = it.next();
                    if (sk.isReadable()){
                        ByteBuffer buffer = ByteBuffer.allocate(1024);
                        dc.receive(buffer);
                        buffer.flip();
                        System.out.println(new String(buffer.array(),0,buffer.limit()));
                        buffer.clear();
                    }
                    it.remove();
                }

            }
        } catch (IOException e) {
            e.printStackTrace();
        }

    }
}

